<template>

  <!-- 加载时显示固定数量的骨架屏 -->
  <div v-if="loading">
    <van-skeleton title avatar :row="3" v-for="n in 5" :key="n" round/>
  </div>
  <div v-else>
    <van-card
        v-for="user in props.userList"
        style="margin: 4px"
        :desc="user.profile"
        :thumb="user.avatarUrl"
        @clickThumb="doToUserInfo(user)"
    >
      <template #title>
        <div style="margin-bottom: 6px">{{ user.username }}</div>
      </template>
      <template #tags>
        <van-tag plain type="danger" v-for="tag in user.tags" style="margin-right: 8px; margin-top: 8px">
          {{ tag }}
        </van-tag>
      </template>
      <template #footer style="margin-left: 4px; margin-top: 4px">
        <van-button v-if="!followStatusMap[user.id]" size="mini" type="primary" @click="doFollowUser(user.id)"
                    text="交个朋友吧"/>
        <van-button v-if="followStatusMap[user.id]" size="mini" type="warning" @click="doDeleteFollowUser(user.id)"
                    text="取消关注"/>
      </template>
    </van-card>
  </div>

</template>

<script setup lang="ts">

import type {UserType} from "../models/User";
import {useRouter} from "vue-router";
import {showConfirmDialog, showFailToast, showSuccessToast} from "vant";
import {deleteFollowUser, followUser, getFollowStatus} from "../api/Follow.ts";
import {ref, onMounted, watch} from 'vue'

const router = useRouter();

interface UserCardListProps {
  loading: boolean;
  userList: UserType[];
}

// 定义关注状态映射
const followStatusMap = ref<Record<number, boolean>>({});

const initFollowStatus = async () => {
  if (!props.userList || props.userList.length === 0) {
    return;
  }
  // 并行查询所有用户的关注状态
  const promises = props.userList.map(async user => {
    const res = await getFollowStatus(user.id);
    // @ts-ignore
    if (res.code === 0) {
      followStatusMap.value[user.id] = res.data;
    } else {
      // @ts-ignore
      showFailToast("获取用户关注状态失败" + (res.description ? `${res.description}` : ''));
      followStatusMap.value[user.id] = false;
    }
  });
  // 等待所有查询完成
  await Promise.allSettled(promises);
}

// 获取用户关注状态
onMounted(async () => {
  await initFollowStatus();
});

// 定义默认值
const props = withDefaults(defineProps<UserCardListProps>(), {
  loading: true,
  userList: () => [] as UserType[],
})

// 监听 userList 变化，重新初始化
watch(() => props.userList, () => {
  console.log('用户列表更新，重新初始化关注状态');
  initFollowStatus();
});


// 点击用户头像跳转到用户信息页面
const doToUserInfo = (user: UserType) => {
  router.push({
    path: '/user/showInfo',
    query: {
      // 传递用户id
      userId: Number(user.id),
    },
  })
}

/**
 * 关注用户
 * @param id
 */
const doFollowUser = async (id: number) => {
  const result = await followUser(id);
  // @ts-ignore
  if (result.code === 0 && result.data) {
    showSuccessToast("关注成功");
    // 直接更新本地状态，视图自动刷新
    followStatusMap.value[id] = true;
  } else {
    // @ts-ignore
    showFailToast("关注失败" + (result.description ? `${result.description}` : ''));
  }
}

/**
 * 取消关注用户
 * @param id
 */
const doDeleteFollowUser = async (id: number) => {
  showConfirmDialog({
    title: '消息确认',
    message: '您确定要取消关注吗',
  }).then(async () => {
    // on confirm
    const result = await deleteFollowUser(id);
    // @ts-ignore
    if (result.code === 0 && result.data) {
      showSuccessToast("取消关注成功");
      // 直接更新本地状态，视图自动刷新
      followStatusMap.value[id] = false;
    } else {
      // @ts-ignore
      showFailToast("取消关注失败" + (result.description ? `${result.description}` : ''));
    }
  }).catch(() => {
    // on cancel
  });
}


</script>

<style scoped>
.van-toast {
  color: #152b75 !important; /* 确保文字颜色可见，根据实际需求调整 */
  z-index: 9999 !important;
}

</style>